# -*- coding: utf-8 -*-
import json
import requests
from application import settings

graphwalker_url = f'{settings.GRAPHWALKER_URL}/graphwalker'
headers={'Content-Type': 'text/plain'}


def get_path(data):
    """ 调用GraphWalker Rest API，按照模型生成路径"""
    resp = requests.post(f'{graphwalker_url}/load', json=data, headers=headers)
    msg = json.loads(resp.text)
    result = []
    if 'ok' != msg['result']:
        return result
    resp = requests.get(f'{graphwalker_url}/hasNext', headers=headers)
    while 'true' in resp.text:
        next = requests.get(f'{graphwalker_url}/getNext', headers=headers)
        print(next.text)
        msg = json.loads(next.text)
        if 'ok' == msg['result']:
            result.append(msg['currentElementName'])
        resp = requests.get(f'{graphwalker_url}/hasNext', headers=headers)
    return result


def get_statistics():
    """ 调用GraphWalker Rest API，获取结果"""
    res = requests.get(f'{graphwalker_url}/getStatistics', headers=headers)
    return json.loads(res.text)


def reset_generator(data, edges):
    """ 重新生成模型，修改了 ‘generator’ """
    size = len(edges)
    conditions = f'reached_edge({edges[size-1]})'
    data['models'][0]['generator'] = f'a_star({conditions})'
    return data


def generate(data):
    """ 生成路径 """
    results = get_path(data)
    statistics = get_statistics()
    edges = []
    if statistics["edgeCoverage"] != 100:
        for edge in statistics["edgesNotVisited"]:
            edges.append(edge['edgeName'])
    return edges, results


def walk(filePath):
    """ walk 整个模型， 边覆盖 """
    total = set()
    with open(filePath, 'r') as file:
        data = json.load(file)
    edges, results = generate(data)
    total.add(tuple(results))
    while len(edges) > 0:
        print("-------分割线-------")
        data = reset_generator(data, edges)
        edges_tmp, results_tmp = generate(data)
        edges = list(set(edges) & set(edges_tmp))
        if tuple(results_tmp) not in total:
            total.add(tuple(results_tmp))
    return total


if __name__ == '__main__':
    filePath = 'D:/graphwalker/ShoppingCart4.json'
    total = walk(filePath)
    for index, testcase in enumerate(total):
        print(f'{index}, {testcase}')










